// fs_wmall/pages/sjzx/wmdd.js
import PrinterJobs from '../bluetooth/common/print/printerjobs.js'
import printerUtil from '../bluetooth/common/print/printerutil.js'
import util from '../bluetooth/common/print/util.js'
var base = require('../../../utils/lang.js');
const _ = base._
// _t: base._t(),


var app = getApp();
var dsq;
var siteinfo = require('../../../../siteinfo.js');

// 打印
let beServerOrderSize = 100
let toBeServedOrderOnOff = false
let toBeServedOrderLast = []
let toBeServedOrderThis = []

// 退单
let chargebackOnOff = false
let chargebackLast = []

let _lastPrintTime = 0
let _printLineTimer = null

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		root: '',
		isBluetooth: false,
		isOpenBle: false,
		selectedindex: 0,
		topnav: [{
			img: '../../../img/icon/djd.png',
			img1: '../../../img/icon/wdjd.png',
			name: _('待接单')
		}, {
			img: '../../../img/icon/dps.png',
			img1: '../../../img/icon/wdps.png',
			name: _('待送达')
		}, {
			img: '../../../img/icon/dzt.png',
			img1: '../../../img/icon/wdzt.png',
			name: _('待自提')
		}, {
			img: '../../../img/icon/ywc.png',
			img1: '../../../img/icon/wywc.png',
			name: _('已完成')
		}, {
			img: '../../../img/icon/sh.png',
			img1: '../../../img/icon/wsh.png',
			name: _('售后/退款')
		}, ],
		open: false,
		pagenum: 1,
		order_list: [],
		storelist: [],
		mygd: false,
		jzgd: true,
		hide: 1
	},
	dyxpByBt: function(e) {
		const {
			isOpenBle,
			isBluetooth
		} = this.data
		if (!(isOpenBle && isBluetooth)) {
			console.log('打印小票')
			this.dyxp.call(this, e)
			return
		}
		var index = e.currentTarget.dataset.index
		var {
			order_list
		} = this.data
		var _order = order_list[index]
		wx.showModal({
			title: _("提示"),
			content: _("是否确认打印此订单小票？"),
			cancelText: _("否"),
			confirmText: _("是"),
			success: res => {
				this.pickUpOnceM(_order)
			}
		})
	},
	// bluetooth
	//打印一次
	async pickUpOnceM(data) {
		await app.bluetooth.notifyBLECharacteristicValue();
		this.writeBLECharacteristicValue(data);
	},

	//写入控制命令
	writeBLECharacteristicValue(data) {
		// let Qrcode_res = await this.get_Qrcode();
		let printerJobs = new PrinterJobs();
		const _num = data.order.oid
		const _name = data.order.name
		const orderId = data.order.order_num
		const delivery_time = data.order.delivery_time
		const money = data.order.money
		const goodsList = data.good
		const tel = data.order.tel
		const address = data.order.address
		const delivery_tyoe = data.order.order_type

		let payMethod = ''
		if (data.order.pay_type === '1') {
			payMethod = _('微信支付')
		}
		if (data.order.pay_type === '2') {
			payMethod = _('余额支付')
		}
		if (data.order.pay_type === '4') {
			payMethod = _('货到付款')
		}

		printerJobs
			.print(util.formatTime(new Date()))
			.print(printerUtil.fillLine())
			.setAlign('ct')
			.setSize(2, 2)
			.print('#' + _num)
			.setSize(1, 1)
			.print(_name)
			.setSize(2, 2)
			.print(payMethod)

		if (tel) {
			printerJobs
				.setSize(1, 1)
				.print(_('电话') + ':' + tel)
		}

		if (address) {
			printerJobs
				.setSize(1, 1)
				.print(_('地址') + ':' + address)
		}

		printerJobs
			.setSize(1, 1)
			.print(_('订单号') + ':' + orderId)

		if (delivery_tyoe === '1') {
			printerJobs
				.print(_('配送时间') + '：' + delivery_time)
		} else {
			printerJobs
				.print(_('自提时间') + '：' + delivery_time)
		}

		printerJobs
			.setAlign('lt')
			.print(printerUtil.fillAround(_('一号口袋')))

		for (var i = 0; i < goodsList.length; i++) {
			const item = goodsList[i]
			console.log(item)
			printerJobs
				.print(printerUtil.inline(item.name + '*' + item.number, item.money))
		}

		printerJobs
			.print(printerUtil.fillLine())
			.setAlign('rt')
			.print(_('订单金额') + '：￥' + money)
			.setAlign('lt')
			.print(printerUtil.fillLine())
			//.print('备注')
			//.print("无")
			//.print(printerUtil.fillLine())
			//.printQrcode(Qrcode_res)
			.println();

		let buffer = printerJobs.buffer();

		this.printbuffs(buffer);
	},

	printbuffs(buffer) {
		// 1.并行调用多次会存在写失败的可能性
		// 2.建议每次写入不超过20字节
		// 分包处理，延时调用
		const maxChunk = 20;
		const delay = 20;
		const printTime = Math.ceil(buffer.byteLength / maxChunk) * delay
		// 加500是打印机有个异步的操作
		_lastPrintTime = printTime + 500

		for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
			let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
			console.log('打印时间:' + j * delay)
			setTimeout(this.printbuff, j * delay, subPackage);
		}
	},

	printbuff(buffer) {
		app.bluetooth.writeBLECharacteristicValue(buffer);
	},

	hide: function(t) {
		this.setData({
			hide: 1
		})
	},
	psxq: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id,
			sjid = e.currentTarget.dataset.sjid,
			psmode = e.currentTarget.dataset.psmode;
		console.log(oid, sjid, psmode)
		wx.showLoading({
			title: "加载中",
			mask: !0
		}), app.util.request({
			'url': 'entry/wxapp/GetStorePsInfo',
			'cachetime': '0',
			data: {
				store_id: sjid,
				order_id: oid
			},
			success: function(res) {
				console.log(res.data)
				if (psmode == _('达达配送') && res.data.result == null) {
					wx.showModal({
						title: _('提示'),
						content: _('配送信息异常') + res.data,
					})
					return
				}
				a.setData({
					psxx: res.data,
					psmode: psmode,
					hide: 2
				})
			},
		})
	},
	maketel: function(t) {
		var a = t.currentTarget.dataset.tel;
		wx.makePhoneCall({
			phoneNumber: a,
		})
	},
	location: function(t) {
		var lat = t.currentTarget.dataset.lat,
			lng = t.currentTarget.dataset.lng,
			address = t.currentTarget.dataset.address;
		console.log(lat, lng)
		wx.openLocation({
			latitude: parseFloat(lat),
			longitude: parseFloat(lng),
			address: address,
			name: _('位置')
		})
	},
	selectednavbar: function(e) {
		console.log(e)
		this.setData({
			pagenum: 1,
			order_list: [],
			storelist: [],
			mygd: false,
			jzgd: true,
			selectedindex: e.currentTarget.dataset.index,
			status: Number(e.currentTarget.dataset.index) + 1
		})
		this.reLoad();
	},
	doreload: function(status) {
		console.log(status)
		this.setData({
			pagenum: 1,
			order_list: [],
			storelist: [],
			mygd: false,
			jzgd: true,
			selectedindex: status - 1,
			status: status
		})
		this.reLoad();
	},
	kindToggle: function(e) {
		var that = this;
		var index = e.currentTarget.id,
			list = this.data.order_list;
		console.log(index)
		for (var i = 0, len = list.length; i < len; ++i) {
			if (i == index) {
				list[i].open = !list[i].open
			} else {
				list[i].open = false
			}
		}
		this.setData({
			order_list: list
		});
	},
	// 退单
	getChargebackList() {
		const store_id = wx.getStorageSync('sjdsjid')
		const {
			root
		} = this.data
		app.util.request({
			'url': 'entry/wxapp/StoreWmOrder',
			'cachetime': '0',
			data: {
				state: '6,7,8,9,10',
				zt: 2,
				store_id: store_id,
				page: 1,
				pagesize: 10
			},
			success: res => {
				let _list = res.data
				if (chargebackOnOff) {
					_list.map(item => {
						const orderId = item.order.id
						if (!chargebackLast.includes(orderId)) {
							if (wx.getStorageSync('yybb')) {
								console.log('play refund')
								console.log(root + 'addons/fs_wmall/img/refundSound.mp3')
								wx.playBackgroundAudio({
									dataUrl: '',
									dataUrl: root +
										'addons/fs_wmall/img/refundSound.mp3',
									title: _('退单播报'),
								})
							}
						}
					})
				}
				chargebackOnOff = true
				_list.map(item => {
					const orderId = item.order.id
					if (!chargebackLast.includes(orderId)) {
						chargebackLast.push(orderId)
					}
				})
			}
		})
	},
	// m-自动接单,打印小票-start
	getToBeServedList() {
		// 获取待送达订单
		const store_id = wx.getStorageSync('sjdsjid')
		app.util.request({
			'url': 'entry/wxapp/StoreWmOrder',
			'cachetime': '0',
			data: {
				state: 3,
				zt: 2,
				store_id: store_id,
				page: 1,
				pagesize: beServerOrderSize
			},
			success: res => {
				console.log('toBeServedOrderLast')
				console.log(toBeServedOrderLast)
				beServerOrderSize = 10
				let _list = res.data
				// 开关控制 toBeServedOrderThis
				if (toBeServedOrderOnOff) {
					_list.map(item => {
						const orderId = item.order.id
						if (!toBeServedOrderLast.includes(orderId)) {
							toBeServedOrderThis.push(item)
						}
					})
				}
				toBeServedOrderOnOff = true
				// 存储所有待处理订单id
				// toBeServedOrderLast = []
				_list.map(item => {
					const orderId = item.order.id
					if (!toBeServedOrderLast.includes(orderId)) {
						toBeServedOrderLast.push(orderId)
					}
				})

				if (toBeServedOrderThis.length) {
					// 如果有新的订单,执行打印操作
					this.mPrintList()
				}
			}
		})
	},
	mPrintList() {
		console.log("_lastPrintTime:" + _lastPrintTime)
		// _lastPrintTime 记录上一次打印的时间初始值是0
		clearTimeout(_printLineTimer)
		_printLineTimer = setTimeout(() => {
			if (!toBeServedOrderThis.length) {
				console.log('没订单了,停止打印')
				_lastPrintTime = 0
			} else {
				console.log('队列打印')
				const _first = toBeServedOrderThis.shift()
				this.pickUpOnceM(_first)
				// 如果在计算出本次打印之前执行了递归操作,上一次打印时间假设为1s
				if (_lastPrintTime === 0) {
					console.log('_lastPrintTime初始值')
					_lastPrintTime = 1000
				}
				this.mPrintList()
			}
		}, _lastPrintTime)
	},
	// m-自动接单,打印小票-end

	reLoad: function() {
		var that = this,
			status = this.data.status || 1,
			store_id = wx.getStorageSync('sjdsjid'),
			page = this.data.pagenum;
		var wmstatus, zt = ''
		if (status == 1) {
			wmstatus = '2'
		}
		if (status == 2) {
			wmstatus = '3'
			zt = '2'
		}
		if (status == 3) {
			wmstatus = '3'
			zt = '1'
		}
		if (status == 4) {
			wmstatus = '4,5';
		}
		if (status == 5) {
			wmstatus = '6,7,8,9,10';
		}
		console.log(status, wmstatus, zt, store_id, page)
		app.util.request({
			'url': 'entry/wxapp/StoreWmOrder',
			'cachetime': '0',
			data: {
				state: wmstatus,
				zt: zt,
				store_id: store_id,
				page: page,
				pagesize: 10
			},
			success: function(res) {
				console.log('分页返回的列表数据', res.data)
				if (res.data.length < 10) {
					that.setData({
						mygd: true,
						jzgd: true,
					})
				} else {
					that.setData({
						jzgd: true,
						pagenum: that.data.pagenum + 1,
					})
				}
				var storelist = that.data.storelist;
				storelist = storelist.concat(res.data);

				function unrepeat(arr) {
					var newarr = [];
					for (var i = 0; i < arr.length; i++) {
						if (newarr.indexOf(arr[i]) == -1) {
							newarr.push(arr[i]);
						}
					}
					return newarr;
				}
				storelist = unrepeat(storelist)
				that.setData({
					order_list: storelist,
					storelist: storelist
				})
				console.log(storelist)
			}
		});
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		const isWei = base.isWeiFn()
		this.setData({
			isWei
		})
		this.getToBeServedList()
		toBeServedOrderOnOff = false
		toBeServedOrderLast = []
		toBeServedOrderThis = []
		// 蓝牙设置
		const isBluetooth = wx.getStorageSync('mBluetooth')
		this.setData({
			isBluetooth
		})
		if (isBluetooth) {
			let isOpenBle = app.bluetooth.isOpenBle
			this.setData({
				isOpenBle
			})
		}

		var that = this,
			sjdsjid = wx.getStorageSync('sjdsjid'),
			root = siteinfo.siteroot.replace("app/index.php", "");
		console.log(sjdsjid, root)
		console.log('root:' + root)
		this.setData({
			root
		})
		this.reLoad();
		app.setNavigationBarColor(this);
		app.sjdpageOnLoad(this);
		app.util.request({
			'url': 'entry/wxapp/system',
			'cachetime': '0',
			success: function(res) {
				console.log(res.data)
				wx.setStorageSync('system', res.data)
				wx.setNavigationBarTitle({
					title: res.data.wm_name || _('外卖'),
				})
				that.setData({
					xtxx: res.data
				})
			}
		});
		dsq = setInterval(() => {
			// m-获取待送达订单
			this.getToBeServedList()
			this.getChargebackList()
			if (wx.getStorageSync('yybb')) {
				app.util.request({
					'url': 'entry/wxapp/NewOrder',
					'cachetime': '0',
					data: {
						store_id: sjdsjid
					},
					success: (res) => {
						if (res.data == 1) {
							// m-有订单状态,
							wx.playBackgroundAudio({
								dataUrl: root +
									'addons/fs_wmall/template/images/wm.wav',
								title: _('语音播报'),
							})
							this.doreload();
						}
						if (res.data == 2) {
							wx.playBackgroundAudio({
								dataUrl: root +
									'addons/fs_wmall/template/images/dn.wav',
								title: _('语音播报'),
							})
						}
						// if (res.data == 3) {
						//   wx.playBackgroundAudio({
						//     dataUrl: root + 'addons/fs_wmall/template/images/yy.wav',
						//     title: '语音播报',
						//   })
						// }
					},
				})
			} else {
				// clearInterval(dsq)
			}
		}, 10000)
	},
	smhx: function(e) {
		var storeid = wx.getStorageSync('sjdsjid');
		// var path = "zh_vip/pages/my/wdck/hx?scene=2"
		// var tnurl = '/' + path
		// wx.navigateTo({
		//   url: tnurl + '&storeid=' + storeid,
		// })
		wx.scanCode({
			success: (res) => {
				console.log(res)
				var path = res.path
				var tnurl = '/' + path
				wx.navigateTo({
					url: tnurl + '&storeid=' + storeid,
				})
			},
			fail: (res) => {
				console.log('扫码fail')
				// wx.showToast({
				//   title: '二维码错误',
				//   image:'../images/x.png'
				// })
			}
		})
	},
	dyxp: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id;
		console.log(oid)
		wx.showModal({
			title: _("提示"),
			content: _("是否确认打印此订单小票？"),
			cancelText: _("否"),
			confirmText: _("是"),
			success: function(s) {
				if (s.cancel) return !0;
				s.confirm && (wx.showLoading({
					title: _("操作中"),
					mask: !0
				}), app.util.request({
					'url': 'entry/wxapp/QtPrint',
					'cachetime': '0',
					data: {
						order_id: oid,
						type: 1
					},
					success: function(res) {
						console.log(res.data)
						wx.showToast({
							title: _('操作成功'),
							icon: 'success',
							duration: 1000,
						})
					},
				}))
			}
		})
	},
	djjd: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id;
		var _this = this
		var index = e.currentTarget.dataset.index
		var {
			order_list
		} = this.data
		var _order = order_list[index]
		console.log('yjy11')
		console.log(oid)
		console.log(_("提示"))
		console.log(_("是否确认接单？"))
		console.log(_("否"))
		console.log(_("是"))
		
		
		wx.showModal({
			title: _("提示"),
			content: _("是否确认接单？"),
			cancelText: `否`,
			confirmText: `是`,
			success: function(s) {
				if (s.cancel) return !0;
				s.confirm && (wx.showLoading({
					title: _("操作中"),
					mask: !0
				}), app.util.request({
					'url': 'entry/wxapp/JdOrder',
					'cachetime': '0',
					data: {
						order_id: oid
					},
					success: function(res) {
						console.log(res.data)
						if(res.data == '-1'){
							wx.showToast({
								title: "订单失效",
								icon: 'none',
								duration: 1000,
							})
							setTimeout(function() {
								a.doreload(1)
							}, 1000)
							return
						}
						if (res.data == '1') {
							wx.showToast({
								title: _('接单成功'),
								icon: 'success',
								duration: 1000,
							})
							setTimeout(function() {
								a.doreload(2)
							}, 1000)
						} else {
							wx.showToast({
								title: _('请重试'),
								icon: 'loading',
								duration: 1000,
							})
						}
					},
				}))
			}
		})
	},
	jjjd: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id;
		console.log(oid)
		wx.showModal({
			title: _("提示"),
			content: _("是否拒绝接单？"),
			cancelText: _("否"),
			confirmText: _("是"),
			success: function(s) {
				if (s.cancel) return !0;
				s.confirm && (wx.showLoading({
					title: _("操作中"),
					mask: !0
				}), app.util.request({
					'url': 'entry/wxapp/JjOrder',
					'cachetime': '0',
					data: {
						order_id: oid
					},
					success: function(res) {
						console.log(res.data)
						if (res.data == '1') {
							wx.showToast({
								title: _('操作成功'),
								icon: 'success',
								duration: 1000,
							})
							setTimeout(function() {
								a.doreload(5)
							}, 1000)
						} else {
							wx.showToast({
								title: _('请重试'),
								icon: 'loading',
								duration: 1000,
							})
						}
					},
				}))
			}
		})
	},
	wcps: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id;
		console.log(oid)
		wx.showModal({
			title: _("提示"),
			content: _("确认完成此订单？"),
			cancelText: _("否"),
			confirmText: _("是"),
			success: function(s) {
				if (s.cancel) return !0;
				s.confirm && (wx.showLoading({
					title: _("操作中"),
					mask: !0
				}), app.util.request({
					'url': 'entry/wxapp/OkOrder',
					'cachetime': '0',
					data: {
						order_id: oid
					},
					success: function(res) {
						console.log(res.data)
						if (res.data == '1') {
							wx.showToast({
								title: _('操作成功'),
								icon: 'success',
								duration: 1000,
							})
							setTimeout(function() {
								a.doreload(4)
							}, 1000)
						} else {
							wx.showToast({
								title: _('请重试'),
								icon: 'loading',
								duration: 1000,
							})
						}
					},
				}))
			}
		})
	},
	jjtk: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id;
		console.log(oid)
		wx.showModal({
			title: _("提示"),
			content: _("是否拒绝退款？"),
			cancelText: _("否"),
			confirmText: _("是"),
			success: function(s) {
				if (s.cancel) return !0;
				s.confirm && (wx.showLoading({
					title: _("操作中"),
					mask: !0
				}), app.util.request({
					'url': 'entry/wxapp/JjTk',
					'cachetime': '0',
					data: {
						order_id: oid
					},
					success: function(res) {
						console.log(res.data)
						if (res.data == '1') {
							wx.showToast({
								title: _('操作成功'),
								icon: 'success',
								duration: 1000,
							})
							setTimeout(function() {
								a.doreload(5)
							}, 1000)
						} else {
							wx.showToast({
								title: _('请重试'),
								icon: 'loading',
								duration: 1000,
							})
						}
					},
				}))
			}
		})
	},
	tgtk: function(e) {
		var a = this,
			oid = e.currentTarget.dataset.id;
		wx.showModal({
			title: _("提示"),
			content: _("是否通过退款？"),
			cancelText: _("否"),
			confirmText: _("是"),
			success: function(s) {
				if (s.cancel) return !0;
				s.confirm && (wx.showLoading({
					title: _("操作中"),
					mask: !0
				}), app.util.request({
					'url': 'entry/wxapp/TkTg',
					'cachetime': '0',
					data: {
						order_id: oid
					},
					success: function(res) {
						console.log(res.data)
						if (res.data == '1') {
							wx.showLoading({
								title: _("操作中"),
								mask: !0
							})
							setTimeout(function() {
								a.doreload(5)
							}, 1000)
						} else {
							wx.showToast({
								title: _('请重试'),
								icon: 'loading',
								duration: 1000,
							})
						}
					},
				}))
			}
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		this.setData({
			_t: base._t()
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		clearInterval(dsq)
		toBeServedOrderOnOff = false
		toBeServedOrderLast = []
		toBeServedOrderThis = []
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
		console.log('上拉加载', this.data.pagenum)
		var that = this;
		if (!this.data.mygd && this.data.jzgd) {
			this.setData({
				jzgd: false
			})
			this.reLoad();
		} else {}
	}
})
